package com.xxl.job.admin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.util.CookieUtil;
import com.xxl.job.admin.core.util.JacksonUtil;
import com.xxl.job.admin.dao.XxlJobUserDao;
import com.xxl.job.admin.util.CASServiceUtil;
import com.xxl.job.admin.util.XmlUtils;
import com.xxl.job.core.biz.model.ReturnT;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;

/**
 * <p>
 * CAS单点登录客户端登录认证
 * </p>
 *
 * @Author zhoujf
 * @since 2018-12-20
 */
@RestController
@RequestMapping("/cas/client")
public class CasClientController {

	public static final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";

	@Resource
	private XxlJobUserDao xxlJobUserDao;
	
	@Value("${cas.prefixUrl}")
    private String prefixUrl;
	
	
	@GetMapping("/validateLogin")
	public Object validateLogin(@RequestParam(name="ticket") String ticket,
								@RequestParam(name="service") String service,
								HttpServletRequest request,
								HttpServletResponse response) throws Exception {

		ReturnT<XxlJobUser> returnT = null;
		try {
			String validateUrl = prefixUrl+"/p3/serviceValidate";
			String res = CASServiceUtil.getSTValidate(validateUrl, ticket, service);
			final String error = XmlUtils.getTextForElement(res, "authenticationFailure");
			if(StringUtils.isNotEmpty(error)) {
				throw new Exception(error);
			}
			final String principal = XmlUtils.getTextForElement(res, "user");
			if (StringUtils.isEmpty(principal)) {
				throw new Exception("No principal was found in the response from the CAS server.");
			}
			XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(principal);
			if (xxlJobUser == null) {
				return new ReturnT<String>(500, "账号错误");
			}
            returnT = new ReturnT<XxlJobUser>(200,"登录成功");
			returnT.setContent(xxlJobUser);
			String loginToken = makeToken(xxlJobUser);
			CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, true);
	  		
		} catch (Exception e) {
			return new ReturnT<String>(500, "异常");
		}
		return new HttpEntity<>(returnT);
	}

	private String makeToken(XxlJobUser xxlJobUser){
		String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser);
		String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
		return tokenHex;
	}
}
